<template>
  <div
    class="more-actions-popup"
    v-if="visible"
    :style="{
      left: position.left + 'px',
      top: position.top + 'px',
    }"
    @click.stop
  >
    <div class="actions-menu">
      <div
        v-for="action in actions"
        :key="action.key"
        class="action-item"
        @click.stop="handleAction(action.key)"
      >
        <div
          v-if="actionVisible(action)"
          class="action-item-content"
          :style="{ color: getDisplayColor(action) }"
        >
          <div
            v-if="action.icon"
            class="action-icon"
            v-html="action.icon"
          ></div>
          <span>{{ getDisplayLabel(action) }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, onUnmounted } from "vue";

  // 定义操作项类型
  interface ActionItem {
    key: string;
    label: string | string[];
    icon?: string;
    color?: string | string[];
    switchField?: { field: string; value: string | number | boolean };
  }

  // 定义props
  interface MoreActionsPopupProps {
    visible: boolean;
    position: { left: number; top: number };
    actions: ActionItem[];
    row?: Record<string, any>;
  }

  const props = defineProps<MoreActionsPopupProps>();

  // 获取显示的标签文本
  const getDisplayLabel = (action: ActionItem): string => {
    try {
      if (!action || !action.label) {
        return "";
      }

      if (!Array.isArray(action.label)) {
        return action.label;
      }

      // 如果有switchField且提供了有效row数据，根据条件选择label
      if (
        action.switchField &&
        props.row &&
        typeof props.row === "object" &&
        action.switchField.field in props.row
      ) {
        const { field, value } = action.switchField;
        const fieldValue = props.row[field];
        return fieldValue === value
          ? action.label[1] || ""
          : action.label[0] || "";
      } else {
        // 默认显示第一个标签
        return action.label[0] || "";
      }
    } catch (error) {
      console.error("Error in getDisplayLabel:", error);
      return action?.label?.[0] || "";
    }
  };

  // 获取显示的颜色
  const getDisplayColor = (action: ActionItem): string => {
    try {
      if (!action) {
        return "";
      }

      if (!Array.isArray(action.color)) {
        return action.color || "";
      }
      // 如果有switchField且提供了有效row数据，根据条件选择color
      if (
        action.switchField &&
        props.row &&
        typeof props.row === "object" &&
        action.switchField.field in props.row
      ) {
        const { field, value } = action.switchField;
        const fieldValue = props.row[field];
        return fieldValue === value
          ? action.color[1] || ""
          : action.color[0] || "";
      }

      // 默认显示第一个颜色
      return action.color[0] || "";
    } catch (error) {
      console.error("Error in getDisplayColor:", error);
      return action?.color?.[0] || "";
    }
  };

  // 定义emits
  const emit = defineEmits<{
    (e: "close"): void;
    (e: "action", actionKey: string): void;
  }>();

  const handleClickOutside = (event: MouseEvent) => {
    if (props.visible) {
      const popup = document.querySelector(".more-actions-popup");
      if (popup && !popup.contains(event.target as Node)) {
        emit("close");
      }
    }
  };

  // 处理操作点击
  const handleAction = (actionKey: string) => {
    // 确保action事件立即同步发出
    emit("action", actionKey);
    // 不使用setTimeout，直接同步发出close事件
    emit("close");
  };
  const actionVisible = (action: any): boolean => {
    let visible = true;
    if (action.invisible && Array.isArray(action.invisible)) {
      visible = !action.invisible.some((field: string) => props.row?.[field]);
    }
    return visible;
  };
  onMounted(() => {
    document.addEventListener("click", handleClickOutside);
  });

  onUnmounted(() => {
    document.removeEventListener("click", handleClickOutside);
  });
</script>

<style scoped lang="scss">
  $primary-color: #1890ff;
  $success-color: #52c41a;
  $warning-color: #fa8c16;
  $danger-color: #ff4d4f;
  $text-color: #42464e;
  $light-text: rgba(0, 0, 0, 0.5);
  $border-color: #e0e0e0;
  $background-color: #f8f9fa;
  $hover-bg: #e6f7ff;

  .more-actions-popup {
    position: fixed;
    z-index: 1000;
    pointer-events: auto;
  }

  .actions-menu {
    min-width: 120px;
    background: #fff;
    border: 1px solid #dee0e3;
    border-radius: 4px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    overflow: hidden;
    font-size: 14px;
    padding: 8px 0;
  }

  .action-item {
    display: flex;
    align-items: center;
    padding: 0 8px;
    cursor: pointer;
    transition: background-color 0.2s;
  }

  .action-item-content {
    display: flex;
    align-items: center;
    padding: 6px 4px;
    border-radius: 4px;
    cursor: pointer;
    width: 100%;
    color: #141414;
  }
  .action-item-content:hover,
  .action-item-content.active {
    background-color: #f2f2f2;
  }
  .action-icon {
    width: 16px;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 8px;
  }
</style>
